package com.yztc.orangeentertainment.ui.main.findfragment.findmain;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yztc.orangeentertainment.R;
import com.yztc.orangeentertainment.bean.findbean.FindActivityBean;
import com.yztc.orangeentertainment.bean.findbean.FindBannerBean;
import com.yztc.orangeentertainment.bean.findbean.FindChangeDataBean;
import com.yztc.orangeentertainment.bean.findbean.FindInteractBean;
import com.yztc.orangeentertainment.bean.findbean.FindStarBean;
import com.yztc.orangeentertainment.bean.findbean.FindStaractBean;
import com.yztc.orangeentertainment.bean.findbean.FindWewatchBean;
import com.yztc.orangeentertainment.ui.main.findfragment.findadapter.FindActivityAdapter;
import com.yztc.orangeentertainment.ui.main.findfragment.findadapter.FindChangAdapter;
import com.yztc.orangeentertainment.ui.main.findfragment.findadapter.FindRlvAdapter;
import com.yztc.orangeentertainment.ui.main.findfragment.findadapter.FindStarRlvAdapter;
import com.yztc.orangeentertainment.ui.main.findfragment.findadapter.FindViewPagerAdapter;
import com.yztc.orangeentertainment.ui.main.findfragment.findadapter.FindVoteRlvAdapter;
import com.yztc.orangeentertainment.ui.main.findfragment.findpersenter.FindPresenter;
import com.yztc.orangeentertainment.ui.main.findfragment.findui.FindContract;
import com.yztc.orangeentertainment.ui.main.findfragment.findview.IFindView;
import com.yztc.orangeentertainment.ui.main.channalarticle.ChannalArticleActivity;
import com.yztc.orangeentertainment.ui.main.subscribefragment.staritem.StarItemActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by My on 2016/10/5.
 */
public class FindFragment extends Fragment implements IFindView, FindContract.FindChangeView,
        View.OnClickListener {

    @InjectView(R.id.find_search)
    Button findSearch;
    @InjectView(R.id.find_vp)
    ViewPager findVp;
    @InjectView(R.id.find_bottom)
    LinearLayout findBottom;
    @InjectView(R.id.rank_iv)
    ImageView rankIv;
    @InjectView(R.id.find_paihang)
    TextView findPaihang;
    @InjectView(R.id.find_rlv)
    RecyclerView findRlv;
    @InjectView(R.id.find_more)
    TextView findMore;
    @InjectView(R.id.find_change)
    TextView findChange;
    @InjectView(R.id.findvote_rlv)
    RecyclerView findvoteRlv;
    @InjectView(R.id.findaction_rlv)
    RecyclerView findactionRlv;
    @InjectView(R.id.findstar_rlv)
    RecyclerView findstarRlv;
    @InjectView(R.id.bottom_tv)
    TextView bottomTv;
    @InjectView(R.id.bottom_iv)
    ImageView bottomIv;
    @InjectView(R.id.bottom_name)
    TextView bottomName;
    @InjectView(R.id.bottom_renqi)
    TextView bottomRenqi;
    @InjectView(R.id.bottom_jieshao)
    TextView bottomJieshao;
    @InjectView(R.id.bottom_go)
    TextView bottomGo;
    @InjectView(R.id.star_bottom)
    LinearLayout starBottom;

    int page = 2;
    private FindPresenter presenter;
    private FindContract.Presenter changePresenter;

    private List<ImageView> imageViews = new ArrayList<>();
    private Timer timer = new Timer();
    private static final int UPTATE_VIEWPAGER = 0;
    //设置当前 第几个图片 被选中
    private int autoCurrIndex = 0;
    private ImageView[] mBottomImages;//底部只是当前页面的小圆点

    //定时轮播图片，需要在主线程里面修改 UI
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPTATE_VIEWPAGER:
                    if (msg.arg1 != 0) {
                        findVp.setCurrentItem(msg.arg1);
                    } else {
                        //false 当从末页调到首页是，不显示翻页动画效果，
                        findVp.setCurrentItem(msg.arg1, false);
                    }
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
    Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find, null);
        ButterKnife.inject(this, view);
        initView();
        return view;
    }

    public void initView() {
        //初始化数据并设置监听
        findRlv.setLayoutManager(new GridLayoutManager(getActivity(), 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        findvoteRlv.setLayoutManager(new LinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        findactionRlv.setLayoutManager(new StaggeredGridLayoutManager(1,
                StaggeredGridLayoutManager.HORIZONTAL));
        findstarRlv.setLayoutManager(new GridLayoutManager(getActivity(), 3) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        presenter = new FindPresenter(this);
        presenter.getVerticalFromNet(getActivity());

        changePresenter = new com.yztc.orangeentertainment.ui.main.findfragment.findui
                .FindPresenter(this);
        findChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changePresenter.getFindChangeBeanFromNet(page);
                page++;
            }
        });

        findSearch.setOnClickListener(this);
        findMore.setOnClickListener(this);
    }

    @Override
    public void onVerticalSucess(final List<FindBannerBean> findBannerBeens) {
        for (final FindBannerBean bannerBean : findBannerBeens) {
            //viewpager数据
            ImageView iv = new ImageView(getActivity());
            Glide.with(getActivity()).load(bannerBean.getPic()).into(iv);
            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String str = bannerBean.getUrlroute();
                    if (str.endsWith("html")) {
                        Intent intent = new Intent(getActivity(), FindActionActivity.class);
                        String act = str.substring(str.lastIndexOf("a"), str.lastIndexOf("."));
                        intent.putExtra("act", act);
                        getActivity().startActivity(intent);
                    } else {
                        String id = str.substring(str.lastIndexOf("=") + 1);
                        Intent intent = new Intent(getActivity(), ChannalArticleActivity.class);
                        intent.putExtra("id", id);
                        getActivity().startActivity(intent);
                    }
                }
            });
            imageViews.add(iv);
        }
        FindViewPagerAdapter adapter = new FindViewPagerAdapter(imageViews);
        findVp.setAdapter(adapter);

        //创建底部指示位置的导航栏
        mBottomImages = new ImageView[imageViews.size()];

        for (int i = 0; i < mBottomImages.length; i++) {
            ImageView imageView = new ImageView(getActivity());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10, 10);
            params.setMargins(5, 0, 5, 0);
            imageView.setLayoutParams(params);
            if (i == 0) {
                imageView.setBackgroundResource(R.mipmap.btg_icon_priority_0_full);
            } else {
                imageView.setBackgroundResource(R.mipmap.btg_icon_priority_0_normal);
            }

            mBottomImages[i] = imageView;
            //把指示作用的原点图片加入底部的视图中
            findBottom.addView(mBottomImages[i]);

        }
        // 设置自动轮播图片，3s后执行，周期是3s
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = UPTATE_VIEWPAGER;
                if (autoCurrIndex == imageViews.size() - 1) {
                    autoCurrIndex = -1;
                }
                msg.arg1 = autoCurrIndex + 1;
                mHandler.sendMessage(msg);
            }
        }, 3000, 3000);

        findVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int
                    positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // 一定几个图片，几个圆点，但注意是从0开始的
                int total = mBottomImages.length;
                for (int j = 0; j < total; j++) {
                    if (j == position) {
                        mBottomImages[j].setBackgroundResource(R.mipmap.btg_icon_priority_0_full);
                    } else {
                        mBottomImages[j].setBackgroundResource(R.mipmap.btg_icon_priority_0_normal);
                    }
                }
                autoCurrIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void setRecycleviewAdapter(List<FindWewatchBean> wewatchBeens) {
        //大家都在看的数据
        FindRlvAdapter adapter = new FindRlvAdapter(getActivity(), wewatchBeens);
        findRlv.setAdapter(adapter);
    }

    @Override
    public void setFindInteract(List<FindInteractBean> interactBeens) {
        //互动的数据
        FindVoteRlvAdapter adapter = new FindVoteRlvAdapter(getActivity(), interactBeens);
        findvoteRlv.setAdapter(adapter);
    }

    @Override
    public void setFindActivity(List<FindActivityBean> activityBeens) {
        //活动的数据
        FindActivityAdapter activityAdapter = new FindActivityAdapter(getActivity(), activityBeens);
        findactionRlv.setAdapter(activityAdapter);
    }

    @Override
    public void setFindStar(final List<FindStarBean> starBeens) {
        //明星排行数据
        FindStarRlvAdapter adapter = new FindStarRlvAdapter(getActivity(), starBeens);
        findstarRlv.setAdapter(adapter);
    }

    @Override
    public void setFindStaract(final FindStaractBean staractBean) {
        //最佳人气王数据
        bottomTv.setText("上周最佳人气王");
        Glide.with(getActivity()).load(staractBean.getPortrait()).into(bottomIv);
        bottomName.setText(staractBean.getName());
        bottomRenqi.setText(staractBean.getPraise() + "人气");
        bottomJieshao.setText(staractBean.getDescription());
        bottomGo.setText("GO");
        bottomGo.setBackgroundResource(R.drawable.find_bottom);

        findPaihang.setOnClickListener(this);

        starBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //最佳人气王点击事件
                Intent intent = new Intent(getActivity(), StarItemActivity.class);
                intent.putExtra("sid", staractBean.getId() + "");
                startActivity(intent);
            }
        });
    }

    @Override
    public void onVerticalFail(String msg) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击搜索的监听事件
            case R.id.find_search:
                Intent intent = new Intent(getActivity(), FindSearchActivity.class);
                startActivity(intent);
                break;
            //点击更多排行的监听事件
            case R.id.find_paihang:
                intent = new Intent(getActivity(), FindMoreActivity.class);
                startActivity(intent);
                break;
            //点击更多热文的监听事件
            case R.id.find_more:
                intent = new Intent(getActivity(), FindHotActivity.class);
                startActivity(intent);
                break;

        }

    }

    @Override
    public void getFindChangeDataBeanSucess(List<FindChangeDataBean> changeDataBeens) {
        //大家都在看的数据
        FindChangAdapter adapter = new FindChangAdapter(getActivity(), changeDataBeens);
        findRlv.setAdapter(adapter);
    }

    @Override
    public void getFindChangeDataBeanFail(String msg) {

    }
}
